package com.laizhenghua.share.device.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.laizhenghua.share.common.core.domain.R;
import com.laizhenghua.share.device.domain.entity.Region;
import com.laizhenghua.share.device.mapper.RegionMapper;
import com.laizhenghua.share.device.service.IRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * TODO
 *
 * @Description
 * @Author laizhenghua
 * @Date 2025/6/29 14:40
 **/
@Service
public class IRegionServiceImpl extends ServiceImpl<RegionMapper, Region> implements IRegionService {

    @Override
    public List<Region> treeSelect(String rootCode) {
        LambdaQueryWrapper<Region> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Region::getParentCode, rootCode);
        List<Region> regions = baseMapper.selectList(wrapper);
        for (Region region : regions) {
            wrapper.clear();
            wrapper.eq(Region::getParentCode, region.getCode());
            Long count = baseMapper.selectCount(wrapper);
            region.setHasChildren(ObjectUtil.isNotNull(count) && count > 0);
        }
        return regions;
    }

    @Override
    public R<String> getNameByCode(String code) {
        return R.ok(baseMapper.getNameByCode(code));
    }
}
